from django.shortcuts import render
from django.views import View
from ..models.models import Right,UserRole,RolePower,Role
from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from collections import OrderedDict
import copy
from common.views.utils import table_api,success_api,failure_api
from django.db.models import Q
from django.core.paginator import Paginator
# Create your views here.

class LoginUserView(View):
    """登录"""
    def get(self, request):
        username = request.GET.get('username')
        password = request.GET.get('password')
        code_captcha = request.GET.get('captcha')
        code = request.session.get('code')
        user = authenticate(username=username, password=password)
        if user and code_captcha == code:
            login(request, user)
            return success_api(message='登录成功')
        if user and code_captcha != code:
            return failure_api(message='验证码错误')
        else:
            return failure_api(message='账号或密码错误')

class LoginOutView(View):
    """退出登录"""
    @method_decorator(login_required)
    def get(self, request):
        logout(request)
        return success_api(message='退出成功')

class RightListView(View):
    """所有菜单"""
    @method_decorator(login_required)
    def get(self,request):
        filters = []
        page = request.GET.get('page')
        limit = request.GET.get('limit')
        powerId = request.GET.get('powerId')
        title = request.GET.get('title')
        if powerId:
            filters.append(Q(id=powerId))
        if title:
            filters.append(Q(title__contains=title))
        rights = Paginator(Right.objects.filter(*filters).order_by('id'), limit).get_page(page)
        right_dict = [{
            'id': item.pk,
            'title': item.title,
            'icon': item.icon,
            'href': item.href,
            'openType': item.openType,
            'type': item.type,
            'code': item.code,
            'sort': item.sort,
            'enabled': item.enabled,
            'ca_time': item.ca_time.strftime('%Y-%m-%d %H:%M:%S'),
            'up_time': item.up_time.strftime('%Y-%m-%d %H:%M:%S')
        } for item in rights]
        return table_api(result=right_dict,total=rights.paginator.count)

class RightView(View):
    """所有菜单"""
    @method_decorator(login_required)
    def get(self, request):
        # 获取所有的顶级菜单
        departments = Right.objects.filter(parent_id='0').order_by('-id')
        # 构造树状结构
        tree = []
        for department in departments:
            tree.append({
                'id': department.pk,
                'title': department.title,
                'icon': department.icon,
                'href': department.href,
                'openType': department.openType,
                'type': department.type,
                'code': department.code,
                'sort': department.sort,
                'enabled': department.enabled,
                'spread':True,
                'ca_time': department.ca_time.strftime('%Y-%m-%d %H:%M:%S'),
                'up_time': department.up_time.strftime('%Y-%m-%d %H:%M:%S'),
                'children': RightView.get_children(department)
            })

        # 返回 JSON 格式的数据
        return table_api(result=tree)

    @staticmethod
    def get_children(department):
        children = []
        sub_departments = Right.objects.filter(parent_id=department.pk)
        if sub_departments:
            for sub_department in sub_departments :
                children.append({
                    'id': sub_department.pk,
                    'title': sub_department.title,
                    'icon': sub_department.icon,
                    'href': sub_department.href,
                    'openType': sub_department.openType,
                    'type': sub_department.type,
                    'code': sub_department.code,
                    'sort': sub_department.sort,
                    'enabled': sub_department.enabled,
                    'ca_time': sub_department.ca_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'up_time': sub_department.up_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'children': RightView.get_children(sub_department)
                })
            return children
        else:
            return None

class PowerView(View):
    """权限菜单列表"""
    @method_decorator(login_required)
    def get(self,request):
        user_id = request.user.id
        # 权限过滤
        roles = UserRole.objects.filter(user_id=user_id)
        powers,power_list = [],[]
        for role in roles:
            rights = RolePower.objects.filter(role_id=role.role_id.id)
            if role.role_id.enable:
                for right in rights:
                    if right.right_id.enabled:
                        # 权限加入session
                        if right.right_id.code not in power_list:
                            power_list.append(right.right_id.code)
                        # 获取一二级菜单
                        if right.right_id.type == '0' or right.right_id.type == '1':
                            if right.right_id not in powers:
                                powers.append(right.right_id)

        # 权限加入session
        request.session['powers'] = power_list

        power_dict = [
            {
                'id': item.pk,
                'title': item.title,
                'icon': item.icon,
                'href': item.href,
                'openType': item.openType,
                'type': item.type,
                'code': item.code,
                'sort': item.sort,
                'enabled': item.enabled,
                'parent_id': item.parent_id
            } for item in powers
        ]

        power_dict.sort(key=lambda x: x['id'], reverse=True)

        menu_dict = OrderedDict()
        for _dict in power_dict:
            if _dict['id'] in menu_dict:
                # 当前节点添加子节点
                _dict['children'] = copy.deepcopy(menu_dict[_dict['id']])
                _dict['children'].sort(key=lambda item: item['sort'])
                # 删除子节点
                del menu_dict[_dict['id']]
            if _dict['parent_id'] not in menu_dict:
                menu_dict[_dict['parent_id']] = [_dict]
            else:
                menu_dict[_dict['parent_id']].append(_dict)

        return JsonResponse(sorted(menu_dict.get(0), key=lambda item: item['sort']), safe=False)